﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.Diagnostics.Contracts;
using System.ServiceModel;
using System.Collections.ObjectModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

namespace YasharEl.Infrastructure.ObjectFactory.ServiceModel
{
    public class DependencyContainerServiceBehavior : IServiceBehavior
    {
        private readonly IDependencyResolver resolver;
        private readonly IDependencyRegistrar registrar;

        public IDependencyResolver DependencyResolver
        {
            get { return resolver; }
        }

        public DependencyContainerServiceBehavior(IDependencyResolver resolver, IDependencyRegistrar registrar)
        {
            Contract.Requires<ArgumentNullException>(resolver != null, "resolver could not be null.");
            Contract.Requires<ArgumentNullException>(registrar != null, "registrar could not be null.");

            this.resolver = resolver;
            this.registrar = registrar;
        }

        public void AddBindingParameters(ServiceDescription serviceDescription,
            ServiceHostBase serviceHostBase,
            Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
                if (channelDispatcher != null)
                {
                    foreach (EndpointDispatcher endpoint in channelDispatcher.Endpoints)
                    {
                        // TODO : May be we need create new container for each service.
                        endpoint.DispatchRuntime.InstanceProvider = new DependencyContainerInstanceProvider(serviceDescription.ServiceType, resolver, registrar);
                    }
                }
            }
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }
    }
}
